package com.jiusit.redisMain.controller;

import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.json.JSONArray;
import org.json.JSONObject;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.SortingParams;

import com.alibaba.fastjson.JSON;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Logger;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.jfinal.ApiController;
import com.jiusit.common.utils.StringUtil;
import com.jiusit.common.utils.TicketUtil;
import com.jiusit.redisMain.interceptor.UserInterceptor;
import com.jiusit.redisMain.model.WxAccessToken;

@ControllerBind(controllerKey = "/token" ,viewPath="/pages")
@Before(UserInterceptor.class)
public class TokenController extends ApiController {
	private static final Logger log = Logger.getLogger(TokenController.class);
	@Override
	public ApiConfig getApiConfig() {
		ApiConfig ac = new ApiConfig();

		// 配置微信 API 相关常量
		ac.setToken(PropKit.get("token"));
		ac.setAppId(PropKit.get("client_ID"));
		ac.setAppSecret(PropKit.get("client_SERCRET"));
		
		
		/**
		 * 是否对消息进行加密，对应于微信平台的消息加解密方式： 1：true进行加密且必须配置 encodingAesKey
		 * 2：false采用明文模式，同时也支持混合模式
		 */
		ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
		ac.setEncodingAesKey(PropKit.get("encodingAesKey",
				"setting it in config file"));
		return ac;
	}
	public void home() {
		render("index.html");
	}
	public void init() {
		String reqUrl = getPara("reqUrl");
		Map dataMap=TicketUtil.getTicket();
		log.debug("dataMap dataMap=" + dataMap);
		UUID uuid = UUID.randomUUID();
		String noncestr = uuid.toString().replace("-", "");
		String timestamp = Long.toString(System.currentTimeMillis()/1000);
		String signStr = new StringBuilder().append(
				"jsapi_ticket=" + dataMap.get("js_ticket")
				        +"&noncestr=" + noncestr + "&timestamp="
						+ timestamp + "&url=" + reqUrl).toString();
		log.debug("sign string=" + signStr);

		signStr = HashKit.sha1(signStr);
		log.debug("jssdk sign=" + signStr);
		Map wxConfig = new HashMap();
		wxConfig.put("appId", getApiConfig().getAppId());
		wxConfig.put("nonceStr", noncestr);
		wxConfig.put("timestamp", timestamp);
		wxConfig.put("signature", signStr);
		wxConfig.put("callback", reqUrl);
		renderJson(wxConfig);
	}
	public void redis_set() {
		String key = getPara("key");
		String value = getPara("value");
		int exn = getParaToInt("exn");
		
		Cache cache = Redis.use();
		try{
			cache.setex(key, exn, value);
		}catch(Exception e) {
			e.printStackTrace();
		}
		Jedis jedis = cache.getJedis();
		jedis.setex(key, exn, value);
		jedis.close();
		renderText("sucess");
	}
	
	public void index() {
		get();
	}
 
	/**
	 * 获取Token
	 */
	public void get() {
		String callback = getPara("jsoncallback");
		//String accessToken = Redis.use().get("ytv.accessToken");
		Jedis jedis = Redis.use().getJedis();
		String accessToken = jedis.get("ytv.accessToken");
		//检测是否有效   -- 无法检测
		if (StrKit.isBlank(accessToken)) {
			String userAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + PropKit.get("ytvAppId") + "&secret="
					+ PropKit.get("ytvSecret");
			String userAccessTokenData = HttpKit.get(userAccessTokenUrl);
			log.debug("accessToken is refush "+userAccessTokenData);
			if (StrKit.notBlank(userAccessTokenData)) {
				Map userAccessToken = JSON.parseObject(userAccessTokenData, HashMap.class);
				if (userAccessToken!=null && userAccessToken.get("errcode")!=null && Long.valueOf(userAccessToken.get("errcode").toString())==0) {
					accessToken = userAccessToken.get("access_token").toString();
					//Redis.use().setex("ytv.accessToken", 7000, accessToken);
					jedis.setex("ytv.accessToken", 7000, accessToken);
					try {
						WxAccessToken wxAccessToken = new WxAccessToken();
						wxAccessToken.set("access_token", accessToken);
						wxAccessToken.set("token_type", "user");
						wxAccessToken.set("create_time", new Date());
						wxAccessToken.set("expires_in", 7000);
						wxAccessToken.set("refresh_token", "");
						wxAccessToken.save();
					} catch (Exception e) {
						log.debug("save wxAccessToken is error " + e.getMessage());
					}
				}
			}
		} else {
			log.debug("UserAccessToken is use cache: "+accessToken);
		}
		jedis.close();
		if (StrKit.isBlank(callback)) {
			renderText(accessToken);
			return;
		} else {
			renderJson(callback + "(" + JsonKit.toJson(accessToken) + ")");
			return;
		}
	}
	public void testRedis(){
		Jedis jedis = Redis.use().getJedis();
		jedis.set("test1", "testRedis1");
		log.debug(jedis.get("test1"));
		renderJson(jedis.get("test1"));
	}
	//获取匹配某个字符串key对应的value
	public void getAllKey(){
		String from_user=getCookie("fromUser");
		String token=getCookie("token");
		System.out.println("from_user:-------"+from_user);
		System.out.println("token:--------------"+token);//2.00tLEJcF4_ssrB4b8ca323ebXDhqwB
	    String dataStr=HttpKit.get("https://api.weibo.com/2/friendships/friends/bilateral.json?access_token="+token+"&uid="+from_user+"&count=50");
		Map <String,Object> datamap=StringUtil.getMap(dataStr);
		JSONArray array=(JSONArray) datamap.get("users");
		for(int i=0;i<array.length();i++){
			JSONObject obj=(JSONObject)array.get(i);
			Map <String,Object> map1=StringUtil.getMap(obj.toString());
			System.out.println(map1);
			System.out.println(map1.get("id"));
			System.out.println(map1.get("avatar_hd"));
			System.out.println(map1.get("name"));
		}
		Map<String ,String> data=new HashMap<String, String>();
		data.put("text", "测试邀请好友");
		data.put("url", "www.baidu.com");
		data.put("invite_logo", "http://tva4.sinaimg.cn/crop.0.0.1242.1242.1024/50a6f3bajw8f2dlcnnsm2j20yi0yj0w5.jpg");
		String json=URLEncoder.encode(data.toString());
	    String result=HttpKit.post("https://m.api.weibo.com/2/messages/invite.json?access_token="+token+"&uid=1353118650"+"&data="+json,"");
        System.out.println(result);
		Map<String,String> map=new HashMap<String,String>();
		Jedis jedis = Redis.use().getJedis();
		Set<String> set=jedis.keys("test*");
		Iterator<String>iterator= set.iterator();
        while(iterator.hasNext()){
        	String key=iterator.next();
        	String value=jedis.get(key);
        	map.put(key, value);
        	System.out.println(key+"---------"+value);
        }
        renderJson(map);
		}

	
	//往list set和get
		public void lpush(){
			Map<String,String> map=new HashMap<String,String>();
			
			Jedis jedis = Redis.use().getJedis();
			jedis.del("lpush");
			jedis.lpush("lpush", "lpush1");
			jedis.lpush("lpush", "lpush2");
			jedis.lpush("lpush", "lpush3");
			jedis.lpush("lpush", "lpush4");
			jedis.lpush("lpush", "lpush5");
			SortingParams sortPara=new SortingParams();
			sortPara =sortPara.alpha();
			System.out.println(jedis.sort("lpush",sortPara));
			//List<String> list=jedis.lrange("lpush", 0, -1);
			List<String> list=jedis.sort("lpush",sortPara); //排序
			for(String str:list){
				System.out.println(str);
				map.put(str, str);
				}
	        renderJson(list);
	        System.out.println(jedis.get("objStr"));
	        jedis.set("objStr",map.toString());
		}
		//返回随机数,不移除
				public void srandmember(){
					Map<String,String> map=new HashMap<String,String>();
					Jedis jedis = Redis.use().getJedis();
					jedis.sadd("srandmember", "srandmember1");
					jedis.sadd("srandmember", "srandmember2");
					jedis.sadd("srandmember", "srandmember3");
					jedis.sadd("srandmember", "srandmember4");
					jedis.sadd("srandmember", "srandmember5");
					String randStr=jedis.srandmember("srandmember");
					//String randStrSpop=jedis.spop("srandmember");
					System.out.println(randStr);

					
					SortingParams sortPara=new SortingParams();
					sortPara =sortPara.alpha();
					System.out.println(jedis.sort("lpush",sortPara));
					//List<String> list=jedis.lrange("lpush", 0, -1);
					List<String> list=jedis.sort("lpush",sortPara); //排序
					for(String str:list){
						map.put(str, str);
						}
			        renderJson(map);
			        System.out.println(jedis.get("objStr"));
			        jedis.set("objStr",map.toString());
				}
				//返回随机数并从redis中移除
				public void spop(){
					Map<String,String> map=new HashMap<String,String>();
					Jedis jedis = Redis.use().getJedis();
					//jedis.sadd("spop", "spop1");
					//jedis.sadd("spop", "spop2");
					//jedis.sadd("spop", "spop3");
					//jedis.sadd("spop", "spop4");
					//jedis.sadd("spop", "spop5");
					//String randStr=jedis.srandmember("srandmember");
					String randStrSpop=jedis.spop("spop");
					System.out.println(randStrSpop);
					Set<String> set=jedis.smembers("spop");
					Iterator<String>iterator= set.iterator();
			        while(iterator.hasNext()){
			        	String key=iterator.next();
			        	//String value=jedis.get(key);
			        	map.put(key, key);
			        	System.out.println(key+"---------"+key);
			        }
			        renderJson(map);
				}
}
